<?php 
class CommentLwModel extends LW_Model {
    private $mid;     //当前访问者Id
    private $name;    //当前访问者名字
    private $uid;     //当前应用的主UID

    public function __construct($lw_db_configs) {
        $userLwDao	 =	TS_D("User");
        $this->mid		 =	$userLwDao->getLoggedInUser();
        $this->name	 =	$userLwDao->getLoggedInName();
        parent::__construct($lw_db_configs);
    }
    public function getCount($type,$appid) {
        $map['type'] = $type;
        $map['appid'] = $appid;
        $map['toId'] = 0;
        $count = $this->where($map)->field('count(1) as count')->find();
        return $count['count'];
    }
    /**
     * getComment
     * 获取评论数据
     * @access public
     * @return void
     */
    public function get($page,$post) {
        if( $this->mid == $post['mid']) {
            $map['type']  = $post['type'];
            $map['appid'] = $post['id'];
            $map['toId']  = '0';
        }else {
            $map = "(uid = {$this->mid} OR (quietly <> 1 AND uid <>{$this->mid}))  AND toId = 0 AND appid = {$post['id']} AND type = '{$post['type']}'";
        }
        $comment = $this->getComments( $map,"cTime DESC",$page,'findPage' );
        foreach( $comment as $key=>&$value ) {
            unset( $map );
            //子回复
            $map['toId']  = $value['id'];
            $map['type']  = $post['type'];
            $map['appid'] = $post['id'];
            if( $subcomment = $this->getComments( $map,"id ASC",null,"findAll" ) ) {
                $value['subcomment'] = $subcomment;
                unset( $value['subcomment']['data'] );
                $value['isDelete'] = false;
            }
        }
        return $comment;
    }

    public function add($post) {
        $map['comment'] = $post['comment'];
        $map['type']    = $post['type'];
        $map['appid']   = $post['appid'];
        $map['cTime']   = time();
        $map['name']    = $this->name;
        $map['status']  = 0;
        $map['uid']     = $this->mid;
        $map['toId']    = $post['toId'];
        $map['quietly'] = $post['quietly'];
        $result = $map;
        if($add = $this->add($map)) {
            $result['cTime']    = "刚刚";
            $result['id']       = $add;
            $result['face']     = getUserFace( $result['uid'] );
            $result['comment']  = $this->replaceContent( $result['comment'],'mini' );//TODO 表情多应用化
            $result['isDelete'] = true;
            return json_encode(($result));
        }else {
            return false;
        }

    }

    public function notify(array $type,array $data,$appid) {
        $dao = TS_D('Notify');
        $dao->setAppId($appid);
            switch ( true ) {
                case (!empty( $data['toUid'] )): //回复的回复
  					setScore($data['toUid'], 'comment_comment');
                    $notify_list = $this->getAllCommentNotify($data['toId']);
                    
                    // 数据重组
                    $notifyIdList = array();
                    $commentIdList = array();
                    $notifyedUid  = array();
                    foreach ($notify_list as $value){
                    	$notifyIdList[] = $value['notifyId'];
                    	$commentIdList[] = $value['id'];
                    	$notifyedUid[]   = $value['uid'];
                    }
                    
                    //1.1 得所有的已发过的通知Id
                    $notifyed = $notifyIdList;
                    //1.11 将所有已发过的通知时间刷新
                    $this->setNewTime($notifyed);
                    
                    
                    //1.2 得到所有已发过通知的评论的id
                    $commentNotifyed = $commentIdList;
                    //1.22 得到这条父评论下的所有子评论，包括父评论的
                    $parent = $this->where('id='.$data['toId'])->find();
                    $child  = $this->getChildComment($data['toId']);
                    $commentList[] = $parent;
					
                    //求出所有已发的人

                    if($child){
                    	$commentList = array_merge($this->replace($commentList),$child);
                    }
					$notifyBody = $data['title_body'];
					$notifyBody['comment'] = $this->getParantNotifyComment($data['toId']);
	                
                    //1.2222 给这些没有发送通知的评论者发送通知
                        foreach($commentList as $value){
                        	if($value['uid'] != $this->mid && !in_array($value['uid'],$notifyedUid)){

                        		
                        		if(in_array($value['uid'],$notifed)) continue;
                        		$notify = $dao->send( $value['uid'],$type.'_comment',$data['title_data'],$notifyBody );
								$this->setNotifyId($value['id'],$notify,$value['uid']);
								$notifed[] = $value['uid'];
                        	}
                    }

                    
                    break;
                default://评论
                	if($this->mid == $data['uids']) break;
                    setScore($this->mid, 'comment');
                    setScore($data['uids'], 'commented');
                    $notify = $dao->send( $data['uids'],$type.'_comment',$data['title_data'],$data['title_body'] );
					$this->setNotifyId($data['title_body']['id'],$notify,$data['uids']);
            }

        //设置评论的通知发布Id
        return $notify;
    }
    
    
    
    public function getChildComment($id){
    	//先检查是否有子回复
    	if($this->checkChildComment($id)){
    		//有子回复
    		//将所有子回复数据提取出来
    		$map['toId'] = $id;
    		$data  = $this->where($map)->findAll();
    		return $this->replace($data);
    	}
    		
    	//没有子回复。直接返回false;
    	return false;
    }
    

    public function checkChildComment($id){
    	//检查是否有子回复
    	$map['toId'] = $id;
    	$result = $this->where($map)->findAll();
    	return $result?true:false;
    }
    
    private function getCommentNotify($commentId){
    	$map['id'] = $commentId;
    	$result = $this->where($map)->field('notifyId')->find();
    	return $result['notifyId'];
    }
    
    private function setNotifyId($commentId,$notifyId,$uid){
    	$dao = TS_D('NotifyRelationship');
		$dao->addRelation($commentId,$notifyId,$uid);
    	return true;
    }
    
    private function getAllCommentNotify($commentId){
    	$dao = TS_D('NotifyRelationship');
    	$map['toId'] = $commentId;
    	$result = $this->where($map)->field('id')->findAll();
    	$commentList = array();
		foreach ($result as $value){
			$commentList[] = $value['id'];
		}
		$commentList[] = $commentId;
		//取得通知的Id列表
		$notify = $dao->findNotify($commentList,$this->mid);
		return $notify;
    }
    
    private function getParantNotifyComment($id){
    	$map['id'] = $id;
    	$comment = $this->where($map)->field('comment')->find();
    	$result = $this->replaceContent($comment['comment'],$type);
    	return $result;
    }
    /**
     * getComments
     * 获取评论
     * @param mixed $map
     * @access private
     * @return void
     */
    private function getComments( $map,$order,$page,$method ) {

    //获取评论数据
        $comment = $this->where( $map )->order( $order )->findAll();

        //如果没有，返回false
        if( !$comment ) {
            return false;
        }

        return  $comment = $this->replace( $comment );
    }
	private function setNewTime($id){
		$dao = TS_D('Notify');
		if(is_array($id)){
			foreach($id as $key => $value){
				$uid =$dao->where('id='.$value)->field('uid')->find();
				if($uid['uid'] == $this->mid) unset($id[$key]);
			}
			$map['id'] = array('in',$id);
		}else{
			$uid =$dao->where('id='.$id)->field('uid')->find();
			if($uid['uid'] == $this->mid) return;
			$map['id'] = $id;
		}
		if($uid['uid'] == $this->mid) return;
        $save['cTime'] = time();
        $save['new'] = 1;
       	$result =  $dao->where($map)->save($save);
       	return $id;
	}
    private function replace( $data ) {
        foreach( $data as $key=>&$value ) {
            $value['face']       = getUserFace( $value['uid'] );
            $value['cTime']      = friendlyDate( $value['cTime'] );
            $value['comment']    = $this->replaceContent( $value['comment'],'mini' );//TODO 表情多应用化
            $value['isDelete']   = (( $this->mid == $value['uid'] )|| $this->mid == $this->uid)?true:false;
        //悄悄话
        }
        return $data;
    }

    /**
     * replaceContent
     * 替换内容
     * @param mixed $content
     * @access private
     * @return void
     */
    private function replaceContent( $content,$type ) {
    //TODO 每一个应用可以应用一套表情
        $path = __PUBLIC__."/images/biaoqing/mini/";//路径
        $smile = ts_cache( "smile_mini" );
        //循环替换掉文本中所有ubb表情
        foreach( $smile as $value ) {
            $img = sprintf("<img title='%s' src='%s%s'>",$value['title'],$path,$value['filename']);
            $content = str_replace( $value['emotion'],$img,$content );
        }
        return $content;
    }


}
?>
